//
//  TYLevelsView.m
//  VoiceMemoDemo
//
//  Created by 马天野 on 2018/8/5.
//  Copyright © 2018年 kangarootec. All rights reserved.
//

#import "TYLevelsView.h"
#import "TYLevelPairs.h"
#import "TYRecorderTool.h"

@interface TYLevelsView(){
    float originX;
}

@end

@implementation TYLevelsView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
        self.clipsToBounds = YES;
        originX = 0;
    }
    return self;
}

#pragma mark - DRAW RECT
- (void)drawRect:(CGRect)rect {
    float linearLevel = self.levelPairs.linearLevel;
    
//    float linearLevel = pairs.linearPeakLevel;
//    NSLog(@"\n linearLevel=%f \n peakLevel=%f",linearLevel,peakLevel);
    
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    bezierPath.lineWidth = 1;
    
    float currentY = 120;
    float moveY = linearLevel*400 + currentY + 5;
    float margin = 4;
    originX=originX + margin;

    //当前点
    [bezierPath moveToPoint:CGPointMake(originX, currentY - moveY/2.0)];
    //移动点linearLevel*100, peakLevel*100
    [bezierPath addLineToPoint:CGPointMake(originX, moveY/2.0)];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = ContentTextColor.CGColor;
    shapeLayer.fillColor = ContentTextColor.CGColor;
    shapeLayer.path = bezierPath.CGPath;
    [self.layer addSublayer:shapeLayer];
    
    self.frame = CGRectMake(self.frame.origin.x - margin, self.frame.origin.y, self.frame.size.width + margin, self.frame.size.height);
}

#pragma mark - Method
- (void)resetLevelMeter {
//    [self.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    NSArray<CALayer *> *subLayers = self.layer.sublayers;
    NSArray<CALayer *> *removedLayers = [subLayers filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject isKindOfClass:[CAShapeLayer class]];
    }]];
    [removedLayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperlayer];
    }];
    originX = 0;
}

#pragma mark - UI
- (void)setupUI {
    self.backgroundColor = [UIColor clearColor];
}

@end
